package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryLsit() {
        //1.先去缓存中查询全部分类标签
        List<String> typeList = stringRedisTemplate.opsForList().range("shopType", 0, -1);
        //2.新建一个集合用来转换后商品对象
        List<ShopType> ShopTypeList = new ArrayList<>();
        //3.如果从redis中获取的分类标签不为空 则将序列化后的json字符串转换为标签对象并添加进集合中
        if (!CollectionUtils.isEmpty(typeList)) {
            for (String typeJson : typeList) {
                ShopType bean = JSONUtil.toBean(typeJson, ShopType.class);
                ShopTypeList.add(bean);
            }
            //3.转换后的标签集合使用stream流根据对象属性进行排序后收集进集合中并返回
            return ShopTypeList.stream().sorted(Comparator.comparing(ShopType::getSort)).collect(Collectors.toList());
        }
        //4.如果redis中不存在取数据库中查询分类标签集合并排序
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //5.将从数据库中查询出的分类标签存储金redis中
        for (ShopType shopType : shopTypes) {
            stringRedisTemplate.opsForList().leftPush("shopType", JSONUtil.toJsonStr(shopType));
        }
        //6.返回
        return shopTypes;
    }
}
